package com.lsl.test;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author lishuailong
 * @create 2020-07-10 15:55
 */
public class TCPtest2 {
    /**
     * 客户端
     */
    @Test
    public void client(){
        Socket socket=null;
        OutputStream os=null;
        BufferedInputStream inputStream=null;
        try {
            InetAddress inetAddress =InetAddress.getByName("192.168.30.114");
            socket = new Socket(inetAddress,8899);
            os = socket.getOutputStream();

            inputStream = FileUtil.getInputStream("C:\\Users\\admin\\Pictures\\222.png");
            IoUtil.copy(inputStream,os);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(os);
            IoUtil.close(socket);
        }
    }

    /**
     * 服务端
     */
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket=null;
        Socket accept=null;
        InputStream inputStream=null;
        BufferedOutputStream outputStream=null;
        try {
            serverSocket = new ServerSocket(8899);
           // while (true){

                accept = serverSocket.accept();
                inputStream = accept.getInputStream();
                //String fileType = FileTypeUtil.getType(inputStream);
                String fileName = IdUtil.simpleUUID();

                String fileType = "jpg";
               // String fileName = "adc";
                outputStream = FileUtil.getOutputStream("C:\\Users\\admin\\Pictures\\img\\"+ fileName+"."+fileType);
                IoUtil.copy(inputStream,outputStream);
          //}


        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(accept);
            IoUtil.close(serverSocket);
        }


    }
}
